<?php
class CashbonusController extends BaseController
{
    public $db;
    public $userInfo;
    public $data;
    // {$url}/cashbonus/commit 订单提交
    public function commitAction()
    {
        // ignore_user_abort(true); // 设定关闭浏览器也执行程序
        set_time_limit(0); // 设定响应时间不限制，默认为30秒
        $this->db = $this->mysql();
        while (true) {
            $data = $this->db->select('cash_bonus_queue', '*', [
                'LIMIT' => 30,
                'type'  => ['首充','加入会员'],
                
            ]);

            if ($data) {
                foreach ($data as $key => $value) {
                    $res = $this->db->has('user', [
                        'user_number' => $value['user_number'],
                        'deletetime'  => null,
                    ]);

                    if ($res == false) {
                        $this->db->delete('cash_bonus_queue', [
                            'user_number' => $value['user_number'],
                        ]);
                    }
                                        $res = $this->db->has('cecharge_order', [
                        'pay_list'     => '订单超时',
                        'order_number' => $value['order_number'],
                    ]);

                    if ($res == true) {
                        $this->db->delete('cash_bonus_queue', [
                            'order_number' => $value['order_number'],
                        ]);
                        continue;
                    }

                    switch ($value['type']) {
                        case '首充':
                            $this->FirstRecharge($value);
                            break;
                        case '加入会员':
                            $this->openvip($value);
                            break;

                        case '购买商品':
                            // $this->buyShop($value);
                            break;
                        case '充值话费':
                           // $this->recharge($value);
                            break;
                        default:
                            # code...
                            break;
                    }
                }
            }
            sleep(1);
            // 设定定时任务终止条件
            if (file_exists('lock.txt')) {break;}
        }
        return false;
    }

    public function FirstRecharge($data)
    {
              $this->data = $data;
        // 查询用户是否已经给上级返现过
        $this->userInfo = $this->db->get('user', '*', [
            'user_number' => $data['user_number'],
            'deletetime'  => null,
            'state'       => 'normal',
        ]);
        // 如果已经返现过或者没有上一级则删除该记录
        if ($this->userInfo['first_charge'] == '已返现' || $this->userInfo['inviter'] == '') {
            $this->db->delete('cash_bonus_queue', [
                'id' => $data['id'],
            ]);
        }

        // 如果没有获得过，则进行返现，并写入资金变动
        $this->db->action(function ($database) {
            // 获取当前商品首充返现比例
            $res = $database->get('cecharge_order', '*', [
                'order_number' => $this->data['order_number'],
                // 'status'       => 'success',
                'deletetime'   => null,
            ]);
            if (is_null($res) || $res['status'] == 'error') {
                dump_log('首充返现： ' . $this->data['order_number'] . ' 状态： 未获取到订单', 'cash_bonus_error');
                $database->delete('cash_bonus_queue', [
                    'id' => $this->data['id'],
                ]);
                dump_log('首充返现： ' . $this->data['order_number'] . ' 状态： 失败订单删除', 'cash_bonus_error');
                return true;
            }
            if ($res['status'] != 'success') {
                return false;
            }
            $orderInfo = json_decode($res['shop_info'], true);

            $card_member = $orderInfo['card_member'] * $this->data['amount'];

            // 获取上一级用户信息
            $account_balance = $database->get('user', 'account_balance', [
                'user_number' => $this->userInfo['inviter'],
            ]);
            // 加入资金变动明细
            $database->insert('user_money_log', [
                'user_number' => $this->userInfo['inviter'],
                'before'      => $account_balance,
                'money'       => $orderInfo['card_member'],
                'after'       => $account_balance + $orderInfo['card_member'],
                'state'       => '下级首充话费返现',
                'type'        => '收入',
                'other'       => $this->userInfo['user_number'],
                'createtime'  => time(),
            ]);
            if ($database->id() < 1) {
                dump_log('首充返现： ' . $this->data['order_number'] . ' 状态： 加入资金变动失败', 'cash_bonus_error.txt');
                return false;
            }
            // 更新上级数据
            $res = $database->update('user', [
                'income[+]'          => $orderInfo['card_member'],
                'account_balance[+]' => $orderInfo['card_member'],
                // 'withdrawals'        => $card_member,

            ], ['user_number' => $this->userInfo['inviter']]);
            if ($res->rowCount() == 0) {
                dump_log('首充返现： ' . $this->data['order_number'] . ' 状态： 更新上级用户数据失败', 'cash_bonus_error.txt');
                return false;
            }

            // 修改自身状态
            $res = $database->update('user', [
                'first_charge' => '已返现',

            ], ['user_number' => $this->userInfo['user_number']]);
            if ($res->rowCount() == 0) {
                dump_log('首充返现： ' . $this->data['order_number'] . ' 状态： 更新自己数据失败', 'cash_bonus_error.txt');
                return false;
            }
            $database->delete('cash_bonus_queue', [
                'id' => $this->data['id'],
            ]);
            dump_log('首充返现： ' . $this->data['order_number'] . ' 状态： 成功', 'cash_bonus_success.txt');
            echo date('Y-m-d H:i:s') . $this->userInfo['user_number'] . '给' . $this->userInfo['inviter'] . '首充返现' . $orderInfo['card_member'] . '元';
            return true;
        });
    }

    public function openvip($data)
    {
        $this->data = $data;
        $this->userInfo = $this->db->get('user', '*', [
            'user_number' => $data['user_number'],
            'deletetime'  => null,
            'state'       => 'normal',
        ]);

        if ($this->userInfo['vip_charge'] == '已返现' || $this->userInfo['inviter'] == '') {
            $this->db->delete('cash_bonus_queue', [
                'id' => $data['id'],
            ]);
        }
        $this->db->action(function ($database) {
            $res = $database->get('open_vip_order', 'vip_group_info', [
                'order_number' => $this->data['order_number'],
                'paytime[>]'   => 0,
                'deletetime'   => null,
            ]);
            if (is_null($res)) {
                dump_log('开通VIP返现： ' . $this->data['order_number'] . ' 状态： 未获取到订单', 'cash_bonus_error.txt');
                 $database->delete('cash_bonus_queue', [
                    'id' => $this->data['id'],
                ]);
                dump_log('开通VIP返现： ' . $this->data['order_number'] . ' 状态： 失败订单删除', 'cash_bonus_error');
                return true;
            }
            $orderInfo = json_decode($res, true);
            $account_balance = $database->get('user', 'account_balance', [
                'user_number' => $this->userInfo['inviter'],
            ]);

            $database->insert('user_money_log', [
                'user_number' => $this->userInfo['inviter'],
                'before'      => $account_balance,
                'money'       => $orderInfo['invitation_to_cash_back'],
                'after'       => $account_balance + $orderInfo['invitation_to_cash_back'],
                'state'       => '下级开通VIP返现',
                'type'        => '收入',
                'other'       => $this->userInfo['user_number'],
                'createtime'  => time(),
            ]);
            if ($database->id() < 1) {
                dump_log('开通VIP返现： ' . $this->data['order_number'] . ' 状态： 加入资金变动失败', 'cash_bonus_error.txt');
                return false;
            }

            $res = $database->update('user', [
                'income[+]'          => $orderInfo['invitation_to_cash_back'],
                'account_balance[+]' => $orderInfo['invitation_to_cash_back'],
            ], ['user_number' => $this->userInfo['inviter']]);

            if ($res->rowCount() == 0) {
                dump_log('开通VIP返现： ' . $this->data['order_number'] . ' 状态： 更新上级用户数据失败', 'cash_bonus_error.txt');
                return false;
            }

            $res = $database->update('user', [
                'vip_charge' => '已返现',

            ], ['user_number' => $this->userInfo['user_number']]);
            if ($res->rowCount() == 0) {
                dump_log('开通VIP返现： ' . $this->data['order_number'] . ' 状态： 更新自己数据失败', 'cash_bonus_error.txt');
                return false;
            }
            $database->delete('cash_bonus_queue', [
                'id' => $this->data['id'],
            ]);
            dump_log('开通VIP返现： ' . $this->data['order_number'] . ' 状态： 成功', 'cash_bonus_success.txt');
            echo date('Y-m-d H:i:s') . $this->userInfo['user_number'] . '给' . $this->userInfo['inviter'] . '开通VIP返现：' . $orderInfo['invitation_to_cash_back'] . '元';
            return true;
        });
    }

    public function recharge($data)
    {

        $this->data = $data;

        $this->userInfo = $this->db->get('user', '*', [
            'user_number' => $data['user_number'],
            'deletetime'  => null,
            'state'       => 'normal',
        ]);

  
        $this->orderInfo = $this->db->get('cecharge_order', '*', [
            'order_number' => $data['order_number'],
            'deletetime'   => null,
            'pay_list'     => '已支付',
            'status'       => 'success',
        ]);

        if (is_null($this->orderInfo)) {
            return false;
        }

        if ($this->orderInfo['return_state'] == '已返现' || $this->userInfo['inviter'] == '') {
            $this->db->delete('cash_bonus_queue', [
                'id' => $data['id'],
            ]);
        }

 
        $this->db->action(function ($database) {
            $shop_info = json_decode($this->orderInfo['shop_info'], true);
            if (is_null($this->orderInfo['cashback_config']) || $this->orderInfo['cashback_config'] == 'null') {
                dump_log('购买商品返现： ' . $this->data['order_number'] . ' 状态： 无需返现', 'recharge');
                $this->db->delete('cash_bonus_queue', [
                    'id' => $this->data['id'],
                ]);
                $res = $database->update('cecharge_order', [
                    'return_state' => '无需返现',

                ], ['order_number' => $this->orderInfo['order_number']]);
                return true;
            }
            echo '<pre>';
            var_dump('享受广告优惠', $this->orderInfo['watch_advertisements']);
            var_dump('享受分享优惠', $this->orderInfo['sharing_preferences']);
            $this->orderInfo['cashback_config'] = json_decode($this->orderInfo['cashback_config'], true);
            if ($this->orderInfo['watch_advertisements'] > 0 || $this->orderInfo['sharing_preferences'] > 0) {
                $first_card_member = $this->orderInfo['cashback_config']['first_class_sale_preferential'];
                $two_card_member   = $this->orderInfo['cashback_config']['two_stage_sale_preferential'];
            } else {
   
                $first_card_member = $this->orderInfo['cashback_config']['first_class_sale'];
                $two_card_member   = $this->orderInfo['cashback_config']['two_stage_sale'];
            }
            var_dump('第一级返销金额：', $first_card_member);
            var_dump('第二级返销金额：', $two_card_member);

            $userInfo = $database->get('user', '*', [
                'user_number' => $this->userInfo['inviter'],
                'state'       => 'normal',
                'deletetime'  => null,
            ]);

            if (!is_null($userInfo)) {

                if ($userInfo['vip_group_id'] != 0 && $userInfo['vip_expiration_time'] > time()) {
                    //
                    var_dump('第一级是会员');

                    $database->debug()->insert('user_money_log', [
                        'user_number' => $this->userInfo['inviter'],
                        'before'      => $userInfo['account_balance'],
                        'money'       => $first_card_member,
                        'after'       => $userInfo['account_balance'] + $first_card_member,
                        'state'       => '下级话费充值返现',
                        'type'        => '收入',
                        'other'       => $this->userInfo['user_number'],
                        'createtime'  => time(),
                    ]);
                    if ($database->id() < 1) {
                        var_dump('第一级加入资金变动失败');
                        dump_log('充值订单返现： ' . $this->data['order_number'] . ' 状态： 第一级加入资金变动失败', 'recharge_error');
                        return false;
                    }
                    $res = $database->update('user', [
                        'income[+]'          => $first_card_member,
                        'account_balance[+]' => $first_card_member,

                    ], ['user_number' => $userInfo['user_number']]);
                    if ($res->rowCount() == 0) {
                        var_dump('更新第一级返现信息失败');
                        dump_log('充值订单返现： ' . $this->data['order_number'] . ' 状态： 更新第一级返现信息失败', 'recharge_error');
                        return false;
                    }
                }

                if ($userInfo['inviter'] != '') {
                    var_dump('查询第二级数据');
                    $topUserNumber = $userInfo['user_number'];
                    $userInfo = $database->get('user', '*', [
                        'user_number'     => $userInfo['inviter'],
                        'vip_group_id[>]' => 0,
                        'state'           => 'normal',
                        'deletetime'      => null,
                    ]);
                    if (!is_null($userInfo) && ($userInfo['vip_group_id'] != 0 && $userInfo['vip_expiration_time'] > time())) {

                        $database->insert('user_money_log', [
                            'user_number' => $userInfo['inviter'],
                            'before'      => $userInfo['account_balance'],
                            'money'       => $two_card_member,
                            'after'       => $userInfo['account_balance'] + $first_card_member,
                            'state'       => '下级话费充值返现',
                            'type'        => '收入',
                            'other'       => $topUserNumber,
                            'createtime'  => time(),
                        ]);
                        if ($database->id() < 1) {
                            var_dump('第一级加入资金变动失败');
                            dump_log('充值订单返现： ' . $this->data['order_number'] . ' 状态： 第一级加入资金变动失败', 'recharge_error');
                            return false;
                        }
                        // 更新上级数据
                        $res = $database->update('user', [
                            'income[+]'          => $two_card_member,
                            'account_balance[+]' => $two_card_member,
                            // 'withdrawals'        => $card_member,

                        ], ['user_number' => $userInfo['user_number']]);
                        if ($res->rowCount() == 0) {
                            var_dump('更新第一级返现信息失败');
                            dump_log('充值订单返现： ' . $this->data['order_number'] . ' 状态： 更新第一级返现信息失败', 'recharge_error');
                            return false;
                        }
                    }

                }

            }

            // 修改订单状态
            $res = $database->update('cecharge_order', [
                'return_state' => '已返现',

            ], ['order_number' => $this->data['order_number']]);
            if ($res->rowCount() == 0) {
                dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 更新自己数据失败', 'recharge');
                return false;
            }
            $database->delete('cash_bonus_queue', [
                'id' => $this->data['id'],
            ]);
            dump_log('话费订单返现： ' . $this->data['order_number'] . ' 状态： 成功', 'recharge');
            // echo date('Y-m-d H:i:s') . $this->userInfo['user_number'] . '给' . $this->userInfo['inviter'] . '下级购买商品返现' . $card_member . '元';
            return true;
        });
    }
    // 购买商品返现
    public function buyShop($data)
    {

        $this->data = $data;
        // 获取用户基础信息
        $this->userInfo = $this->db->get('user', '*', [
            'user_number' => $data['user_number'],
            'deletetime'  => null,
            'state'       => 'normal',
        ]);

        // 查询订单是否已经返现过
        $this->orderInfo = $this->db->get('shop_order', '*', [
            'order_number' => $data['order_number'],
            'deletetime'   => null,
            'status'       => '订单完成',
        ]);
        if (is_null($this->orderInfo)) {
            echo 'no';
            return false;
        }
        // 如果已经返现过或者没有上一级则删除该记录
        if ($this->orderInfo['return_state'] == '已返现' || $this->userInfo['inviter'] == '') {
            $this->db->delete('cash_bonus_queue', [
                'id' => $data['id'],
            ]);
        }

        // 如果没有获得过，则进行返现，并写入资金变动
        $this->db->action(function ($database) {
            $shop_info = json_decode($this->orderInfo['shop_info'], true);
            if ($shop_info['two_class_sale'] == 0 && $shop_info['first_class_sale'] == 0) {
                dump_log('购买商品返现： ' . $this->data['order_number'] . ' 状态： 无需返现', 'buy_shop_error');
                $this->db->delete('cash_bonus_queue', [
                    'id' => $this->data['id'],
                ]);
                $res = $database->update('shop_order', [
                    'return_state' => '无需返现',

                ], ['order_number' => $this->orderInfo['order_number']]);
                return true;
            }
            // 为上一级(2级)用户进行返现
            $card_member = $shop_info['commodity_price'] * $shop_info['first_class_sale'];

            // 更新上级数据
            $res = $database->update('user', [
                'income[+]'          => $card_member,
                'account_balance[+]' => $card_member,
                // 'withdrawals'        => $card_member,

            ], ['user_number' => $this->userInfo['inviter']]);
            if ($res->rowCount() == 0) {
                dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 上级返现信息失败', 'buy_shop_error');
                return false;
            }
            // 获取上一级用户信息
            $userInfo = $database->get('user', '*', [
                'user_number' => $this->userInfo['inviter'],
            ]);
            // 加入资金变动明细
            $database->insert('user_money_log', [
                'user_number' => $this->userInfo['inviter'],
                'before'      => $userInfo['account_balance'],
                'money'       => $card_member,
                'after'       => $userInfo['account_balance'] + $card_member,
                'state'       => '下级购买商品返现',
                'type'        => '收入',
                'other'       => $this->userInfo['user_number'],
                'createtime'  => time(),
            ]);
            if ($database->id() < 1) {
                dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 加入资金变动失败', 'buy_shop_error');
                return false;
            }
            // 判断是否拥有上一级，以及是否需要返现
            if ($userInfo['inviter'] != '' && $shop_info['two'] > 0) {
                // // 获取第第二级返现(1级)
                // $card_member = $shop_info['commodity_price'] * $shop_info['two_class_sale'];

                // // 更新上级数据
                // $res = $database->update('user', [
                //     'income[+]'          => $card_member,
                //     'account_balance[+]' => $card_member,
                //     'withdrawals'        => $card_member,

                // ], ['user_number' => $this->userInfo['inviter']]);
                // if ($res->rowCount() == 0) {
                //     dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 上级返现信息失败', 'buy_shop_error');
                //     return false;
                // }
                // // 获取上一级用户信息
                // $account_balance = $database->get('user', 'account_balance', [
                //     'user_number' => $this->userInfo['inviter'],
                // ]);
                // // 加入资金变动明细
                // $database->insert('user_money_log', [
                //     'user_number' => $this->userInfo['inviter'],
                //     'before'      => $account_balance,
                //     'money'       => $card_member,
                //     'after'       => $account_balance + $card_member,
                //     'state'       => '下级开通VIP返现',
                //     'type'        => '收入',
                //     'other'       => $this->userInfo['user_number'],
                //     'createtime'  => time(),
                // ]);
                // if ($database->id() < 1) {
                //     dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 加入资金变动失败', 'buy_shop_error');
                //     return false;
                // }
            }
            // 修改订单状态
            $res = $database->update('shop_order', [
                'return_state' => '已返现',

            ], ['order_number' => $this->data['order_number']]);
            if ($res->rowCount() == 0) {
                dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 更新自己数据失败', 'buy_shop_error');
                return false;
            }
            $database->delete('cash_bonus_queue', [
                'id' => $this->data['id'],
            ]);
            dump_log('商品订单返现： ' . $this->data['order_number'] . ' 状态： 成功', 'cash_bonus_success.txt');
            echo date('Y-m-d H:i:s') . $this->userInfo['user_number'] . '给' . $this->userInfo['inviter'] . '下级购买商品返现' . $card_member . '元';
            return true;
        });
    }
        public function aAction()
    {
    	$sql = "SELECT users.*,o.order_number FROM `cloud_cecharge_order` o  LEFT JOIN `cloud_user` users  ON o.`user_number`=users.`user_number`  WHERE o.pay_list ='已支付' AND first_charge='未返现' ORDER BY o.id DESC";
		$db = $this->mysql();
		$data = $db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
		foreach ($data as $key => $value){
			$db->insert('cash_bonus_queue',[
					'type' => '首充',
					'order_number'=>$value['order_number'],
					'user_number'=>$value['user_number']
				]);
				print_r($db->error());
		}
		echo '<Pre>';
print_r($data);
return false;
    }


}
